package com.voicechat.firstmet.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import com.voicechat.firstmet.MainActivity;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.WsManager;
import com.voicechat.firstmet.imcontrol.ILoginView;
import com.voicechat.firstmet.imcontrol.LoginHelper;
import com.voicechat.firstmet.imcontrol.RefreshEvent;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.LoginService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: ComePageActivity
 * @Description: 欢迎页面
 * @Author: ljp
 * @CreateDate: 2018/9/11 19:19
 * @Version: 1.0
 */
public class ComePageActivity extends BaseActivity implements ILoginView{
    private String phoneNum;
    private String token;
    private String TAG = "ComePageActivity";
    private static final String[] PERMISSIONS_CONTACT = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA,};
    private static final int REQUEST_CONTACTS = 1000;
    @Override
    protected int setStatusBarColor() {
        return 0;
    }
    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }
    @Override
    protected int loadLayout() {
        return R.layout.activity_come_page;
    }
    @Override
    protected void initLayout(Bundle savedInstanceState) {
       /* if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED|| ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED|| ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)) {
            requestContactsPermissions();
        }else {*/
            phoneNum = SPUtils.getEditoString(SPUtils.SP_PHONE);
            token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
            boolean isEnter = SPUtils.getEditorBoolean("isEnter");
            String deviceInfo = PhoneUtils.getDeviceInfo(context);
            if (isEnter) {
                if (!"".equals(phoneNum) && null != phoneNum
                        && !"".equals(token) && null != token) {//此处还需要判断token是否过期，以及是否填写资料。
                    LoginService.dataValidation(phoneNum, token, deviceInfo).subscribe(result -> {
                        Log.i(TAG, "initLayout: ----result----" + result);
                        if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_INFODATA) {//用户未完善资料
                            Intent intent = new Intent(this, RegisterActivity.class);
                            intent.putExtra("mobile", phoneNum);
                            startActivity(intent);
                            finish();
                        } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                            //设置刷新监听
                            RefreshEvent.getInstance();
                            LoginHelper loginHelper = new LoginHelper(this);
                            MySelfInfoBean.ObjectBean mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                                    SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
                            String editoString = SPUtils.getEditoString(SPUtils.SP_USERSIG);
                            WsManager.getInstance(context).init(mySeleInfo.getId());
                            //startActivity(new Intent(this, MainActivity.class));
                            loginHelper.login(mySeleInfo.getId(), editoString);
                        } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_FAIL) {//token过期
                            startActivity(new Intent(this, LoginActivity.class));
                            finish();
                        } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {//token失效
                            startActivity(new Intent(this, LoginActivity.class));
                            finish();
                        } else {
                            startActivity(new Intent(this, LoginActivity.class));
                            finish();
                        }
                    }, throwable -> {
                        startActivity(new Intent(this, LoginActivity.class));
                        finish();
                        Log.i(TAG, "initLayout: --------" + throwable.toString());
                    });
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                    finish();
                }
            } else {
                startActivity(new Intent(this, GuidePageActivity.class));
                finish();
            }
        //}
    }
    @Override
    public void updateLoginState(boolean state) {
        Log.i(TAG, "updateLoginState: --------"+state);
        
    }

    @Override
    public void onLoginSDKSuccess() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
        Log.i(TAG, "onLoginSDKSuccess: ------登录成功---");

    }

    @Override
    public void onLoginSDKFailed(int errCode, String errMsg) {
        Log.i(TAG, "onLoginSDKFailed: ----------"+errMsg);
        Log.i(TAG, "onLoginSDKFailed: -----errCode-----"+errCode);
        startActivity(new Intent(this, LoginActivity.class));
        finish();

    }

    @Override
    public void onLogoutSDKSuccess() {

    }

    @Override
    public void onLogoutSDKFailed(int errCode, String errMsg) {

    }

    @Override
    protected void onStart() {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED|| ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED|| ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)) {
            requestContactsPermissions();
        }
        super.onStart();
    }
    /**
     * 权限判断
     */
    private void requestContactsPermissions() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)
                || ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)||ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)
                ) {
            // Log.i(TAG, "requestContactsPermissions: -----" + "--------------");
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("隐隐申请权限");
            builder.setTitle("提示");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat
                            .requestPermissions(activity, PERMISSIONS_CONTACT,
                                    REQUEST_CONTACTS);
                    dialog.dismiss();//此处换成删除，这是一个结束返回
                }
            });
            builder.setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setCancelable(false);
            builder.create().show();
        } else {
            ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS);
        }
    }
}
